package unamur.iodass.communication;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.Socket;
import java.net.UnknownHostException;

import org.apache.log4j.Logger;

import unamur.iodass.registration.ParcelDeliveryHandler;


/**
 * Gestion des Communications
 * 
 * @author Cherchem, Marchal
 * Inspiré du code de Dawagne Bruno du projet IALTM Sysdis
 */



public class Communication {
	private static final Logger logger = Logger.getLogger(Communication.class);
	
	
	public static final int ONLINE_LIBRARY_PORT = 7777;
	
	private static volatile Communication instance;
	private Server server;

	private Communication() {
		server = new Server();
	}
	
	public static Communication getInstance() {
		if (instance == null) {
			synchronized (Communication.class) {
				if (instance == null) {
					instance = new Communication();
				}
			}
		}
		return instance;
	}
	
	public void startServer() {
		server.start();
	}
	
	public void stopServer() {
		server.stop();
	}
	
	
	// Send an object via TCP
	public void async(Object object, String ip, int port) {
		InetAddress inetIP = null;
		try {
			inetIP = InetAddress.getByName(ip);
		} catch (UnknownHostException e) {
			logger.error(e);
		}
		
		try {
			Socket socket = new Socket(inetIP, port);
			ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
			oos.writeObject(object);
			socket.close();
		} catch (IOException e) {
			logger.error(e);
			// TODO
		}
	}


}
